﻿/*
#------------------------------------------------------------------------------
#-- Program Name:	[dbo].[spTSX_register_msx]
#-- Purpose:		Add a new target server to the master server
#--	Last Update:	08/26/2014
#--					For a complete history - please review comments in Version
#--					Control.
#------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[spTSX_register_msx]
(
	@msx_server_name		sysname
)
AS

--- Declare Local Variables
DECLARE @server_name sysname
DECLARE @oper_name SYSNAME, @oper_email SYSNAME, @start_time INT, @end_time INT

--- Remove any existing MSX Server that is not the requested MSX server
IF NOT EXISTS (SELECT TOP 1 * FROM [msdb].[dbo].[sysoriginatingservers] WHERE master_server = 1 AND originating_server = @msx_server_name)
  BEGIN
	IF EXISTS (SELECT TOP 1 * FROM [msdb].[dbo].[sysoriginatingservers] WHERE master_server = 1)
		EXEC [msdb].[dbo].sp_msx_defect

	--- Add the MSXOperator Account
	SELECT @oper_name = N'MSXOperator', @oper_email = N'$(AdminEmailAccount)@$(AdminEmailDomainName)', @start_time = 90000, @end_time = 180000
	IF NOT EXISTS ( SELECT * FROM [msdb].[dbo].[sysoperators] WHERE name = @oper_name )
		EXECUTE [msdb].[dbo].[sp_add_operator] @name = @oper_name
	EXECUTE [msdb].[dbo].[sp_update_operator] @name = @oper_name, @enabled = 1, @email_address = @oper_email,
										@weekday_pager_start_time = @start_time, @weekday_pager_end_time = @end_time,
										@saturday_pager_start_time = @start_time, @saturday_pager_end_time = @end_time,
										@sunday_pager_start_time = @start_time, @sunday_pager_end_time = @end_time,
										@pager_days = 0

	--- Enlist with the MSX Server
	EXECUTE	[msdb].[dbo].[sp_msx_enlist] @msx_server_name = @msx_server_name, @location = N''

	--  Add linked server to the MSX Server
	EXEC	[dbo].[spTSX_CreateLinkedServerMSX]
  END
